// 导入axios
import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store/index'
// create an axios instance
// 创建实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    const token = store.getters.token
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  // 解构数据和集中数据处理
  (response) => {
    const { data, message, success } = response.data
    if (success) {
      return data
    } else {
      Message.error(message)
      return Promise.reject(message)
    }
  },
  (error) => {
    // 请求错误
    return Promise.reject(error)
  }
)

export default service
